package main

import (
	"fmt"
	"iot-base/common/custom"
	"iot-base/common/logger"
	"iot-base/common/monitor"
	"iot-base/common/token"
	"iot-base/tm/common/alarmapi"
	_ "iot-base/tm/common/dbinit"
	"iot-base/tm/common/fileapi"
	"iot-base/tm/common/serialapi"
	"iot-base/tm/common/systemapi"
	"iot-base/tm/common/templateapi"

	//"iot-base/common/eventtype"
	"iot-base/tm/common/dataapi"
	_ "iot-base/tm/common/launch"
	"iot-base/tm/common/maintain"
	"iot-base/tm/common/picapi"
	"iot-base/tm/common/serviceapi"
	"iot-base/tm/common/superadmin"

	//"iot-base/tm/common/systemapi"
	"iot-base/tm/common/thingapi"

	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

func init() {

}
func main() {
	logger.Log.Warn("---------TM in edge---------running----------")
	go BeginDiscoverSvr("224.0.0.118", 16665)
	//launch.LaunchService()
	author := token.AuthMiddleware()
	r, api, cfg := thingapi.InitThing(author)
	systemapi.InitAPI(cfg)
	templateapi.InitPickTemplateAPI(cfg)
	custom.InitAPI(api)
	superadmin.InitUser(api)
	thingapi.BeginMsgSocketIO(r)
	thingapi.InitFromCloudAPI(cfg)
	thingapi.InitConfigAPI(cfg)
	picapi.InitPicApi(api)
	serialapi.InitSerialApi(api)

	/*if cfg != nil {
		cfg.Use(token.AuthMiddleware())
		logger.Log.Info("--------------TM create middleware--------------")
	}*/
	if api != nil {
		fileapi.InitAPI(api)
		dataapi.InitDataAPI(api)
		alarmapi.InitAlarmAPI(api)
		serviceapi.InitService(api)
		maintain.InitMaintainAPI(api)
		//api.Use(token.AuthMiddleware())
		file, _ := exec.LookPath(os.Args[0])
		path, err := filepath.Abs(file)
		//dir = "d:/work/node/TS/bin"
		//dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
		dir := filepath.Dir(path)
		if strings.Index(dir, "bin") < 0 {
			dir = dir + "/bin"
		}

		if err != nil {
			log.Fatal(err)
		}
		dir = dir + "/dist"
		fmt.Println("--------------------", dir)

		r.StaticFS("/static", http.Dir(dir))
		r.Static("/js", dir+"/js")
		r.Static("/css", dir+"/css")
		r.Static("/img", dir+"/img")
		r.Static("/assets", dir+"/assets")
		r.LoadHTMLFiles(dir + "/index.html")
		r.GET("/", func(context *gin.Context) {
			context.HTML(http.StatusOK, "index.html", nil)
		})
		r.StaticFS("/ui/", http.Dir(dir))
		lport := fmt.Sprintf(":%v", 16666)
		monitor.InitSelfPicker()

		r.Run(lport)
	}

}
